# coding: utf-8

from flask import request
from flask_restful import Api, Resource
from flask_restful import current_app

from app.api.codes import SUCCESS, PARAMS_ILLEGAL
from app.api.ip_utils import ip_util
from app.api.views import Response
from app.models import get_timestamp
from app.op.constant import UserLevel, UserType
from app.op.models import User, Area
from app.token import AuthToken
from .exhibition_schemas import user_exhibition_schema

api = Api()


@api.resource('/exhibition')
class ExhibitionResource(Resource):
    """
    create by ld_wu 2018-03-02
    """
    store_key = 'exhibition_user_ids'

    def post(self):
        """
        create by ld_wu 2018-03-02
        参加展会活动
        """
        token = request.cookies.get('opc_token')
        user = AuthToken.verify_auth_token(token)
        if not user:
            data, errors = user_exhibition_schema.load(request.form)
            if errors:
                return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))
            ip_info = ip_util.find(request.remote_addr)
            try:
                code = str(int(ip_info[2])) if ip_info.any() else '110000'
            except:
                code = '110000'

            city = Area.get_by_id(code[:4] + '00')
            prov = Area.get_by_id(code[:2] + '0000')
            user = User.get_by_args(
                mobile=data['mobile']
            ) or User.create(
                mobile=data['mobile'],
                nickname=data['nickname'],
                type=UserType.ENGINEER.value,
                level=UserLevel.LEVEL_2.value,
                prov=prov.name,
                city=city.name,
                area_id=city.id
            )
        current_app.redis.zadd(self.store_key, get_timestamp(), user.id)
        return Response()

    def get(self):
        """
        create by ld_wu 2018-03-02
        参加展会的人员列表
        :return:
        """
        user_ids = current_app.redis.zrange(
            self.store_key, 0, -1, withscores=True
        )
        mapping = dict(user_ids)
        users = User.query.filter(
            User.id.in_(mapping.keys())
        ).with_entities(
            User.id,
            User.nickname,
            User.mobile
        )
        info_list = list()
        for each in users:
            user_info = dict(
                id=each.id,
                nickname=each.nickname,
                mobile=each.mobile,
                attended_at=int(mapping.get(str(each.id), 0))
            )
            info_list.append(user_info)
        return Response(SUCCESS, dict(users=info_list))
